<?php
/*
	Copyright 2006, 2007, 2008, 2009, 2010 Bastiaan Grutters
    
    This file is part of Ages of Strife website.

    Ages of Strife website is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Ages of Strife website is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Ages of Strife website.  If not, see <http://www.gnu.org/licenses/>.
 */
include( '../global/initialize.php' );
global $dal, $premium;

$requestedExchange = getPostValue( 'exchange' );
if( $requestedExchange == 10 || $requestedExchange == 100 || $requestedExchange == 1000 ) {
	$statement = $dal->prepare( 'SELECT promotion_points, users.user_id, premium ' .
			'FROM users ' .
			'JOIN ruler ON ruler.user_id = users.user_id ' .
			'WHERE ruler_id = :ruler_id' );
	$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
	$user = $dal->getObject( $statement );
	if( $user->promotion_points >= $requestedExchange ) {
		if( $requestedExchange == 100 ) {
			$premiumTurnsAdd = 20;
		}
		elseif( $requestedExchange == 1000 ) {
			$premiumTurnsAdd = 210;
		}
		elseif( $requestedExchange == 10000 ) {
			$premiumTurnsAdd = 2200;
		}
		if( $user->premium == -1 ) {
			$user->premium = $premiumTurnsAdd;
		}
		else {
			$user->premium += $premiumTurnsAdd;
		}
		$statement = $dal->prepare( 'UPDATE users ' .
				'SET promotion_points = promotion_points - :remove_promotion, premium = :premium ' .
				'WHERE user_id = :user_id' );
		$statement->bindParam( ':premium', $user->premium, PDO::PARAM_INT );
		$statement->bindParam( ':remove_promotion', $requestedExchange, PDO::PARAM_INT );
		$statement->bindParam( ':user_id', $user->user_id, PDO::PARAM_INT );
		$dal->execute( $statement );
		$_SESSION[ 'promotion_exchange_status' ] = number_format( $requestedExchange ) . ' ' . translate( 'promotion points have been exchanged for' ) . ' ' . number_format( $premiumTurnsAdd ) . ' ' . translate( 'premium turns' );
	}
	else {
		$_SESSION[ 'promotion_exchange_status' ] = translate( 'You don\'t have enough promotion points for this exchange.' );
	}
}
else {
	$_SESSION[ 'promotion_exchange_status' ] = translate( 'Please select the number of promotion points you would like to exchange.' );
}

header( 'Location: promotion.php' );
?>
